package com.xingzhe.checkcode.service.impl;

import com.xingzhe.checkcode.service.PhoneOrEmailCoedService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Slf4j
@Service
public class PhoneOrEmailServiceImpl implements PhoneOrEmailCoedService {

    //把yml配置的邮箱号赋值到from
    @Value("${spring.mail.username}")
    //邮件发送人
    private String from;
    //发送邮件需要的对象
    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    RestTemplate restTemplate;
    @Override
    public void sendCode(String number) {
        if (isPhoneNumber(number)) {
            if (number.isEmpty()){
                throw new RuntimeException("至少输入手机号或者邮箱！");
            }
            // http://neteasymusic.xiongsihao.com/captcha/sent?phone=%s
            String wxUrl_template = "http://neteasymusic.xiongsihao.com/captcha/sent?phone=%s";

            String wxUrl = String.format(wxUrl_template,number);

            log.info("调用网易云接口发送验证码, url:{}", wxUrl);

            try {
                ResponseEntity<String> exchange = restTemplate.exchange(wxUrl, HttpMethod.GET, null, String.class);
            }catch (Exception e){
                e.printStackTrace();
                log.debug("验证码发送失败");
            }
        }else {
                String subject = "学成在线";
                //发送一个四位数的验证码,把验证码变成String类型
                String code = generateValidateCode(4).toString();
                String text = "【学成在线】您好，找回密码的验证码为：" + code + "，有效期在10分钟内，请尽快找回！";
                log.info("验证码为：" + code);
                //发送短信
                sendMsg(number,subject,text);
            stringRedisTemplate.opsForValue().set(number,code,10,TimeUnit.MINUTES);
            System.out.println("保存验证码成功");

        }

    }


    public void sendMsg(String to, String subject, String text) {
        //发送简单邮件，简单邮件不包括附件等别的
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        //发送邮件
        javaMailSender.send(message);

    }

    // 判断字符串是否为手机号
    public  boolean isPhoneNumber(String str) {
        String regex = "^1[3-9]\\d{9}$";
        return Pattern.matches(regex, str);
    }

    // 判断字符串是否为邮箱号
    public  boolean isEmail(String str) {
        String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        return Pattern.matches(regex, str);
    }


    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public  Integer generateValidateCode(int length){
        Integer code =null;
        if(length == 4){
            code = new Random().nextInt(9999);//生成随机数，最大为9999
            if(code < 1000){
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
            code = new Random().nextInt(999999);//生成随机数，最大为999999
            if(code < 100000){
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }
}
